$(function(){
	//加载页面评论信息
	loadMessages();
	//QQ表情
	$('.emotion').qqFace({
		id : 'facebox', 
		assign:'content', 
		path : ctx+'/static/qqFace/arclist/'	//表情存放的路径
	});
});

//获取所有评论信息
function loadMessages(page){
	var layindex;
	//封装参数
	var params=new Object();
	params.page=page;
	var url= ctx+"/message/loadMessages.do";
	//发送请求，获取数据
	$.ajax({
	    url:url,
	    type: "POST",
	    async: true,
	    data: params,
	    success: function (data) { 
	    	var result=eval('('+data+')');
	        var success=result.success;
	        if(success==true){
	        	//留言总数
	        	var totalMessage=result.totalMessage;
	        	$("#totalMessage").html(totalMessage);
	        	//调用通用自己的数据填充方法
	        	showData(result,"messageAll");
	        	//分页
	        	var pageCode=result.pageCode;
	        	$("#pageDiv").html(pageCode);
	        }else{
	        	confirm("系统异常！","fail");
	        }	
	    },
	    error: function (XmlHttpRequest, textStatus, errorThrown) {
	        console.log("系统异常！");
	        confirm("系统异常！","fail");
	    },
	    complete:function(XMLHttpRequest, textStatus){
			console.log("url:[ "+url+" ] 请求结果：[ "+textStatus+" ]");
			//关闭加载提示
			//alert(layindex);
		}
	});
}

function showData(result,divid){
	var t=$("#"+divid);//拼接对象
	t.empty();
	var htm='';//拼接内容
	var messageList=result.messageList;
	if(messageList!=null && messageList.length>0){
		$.each(messageList,function(i,message){
			htm+='<div class="comment-show" attr="'+message.id+'">';
		    htm+='    <div class="comment-show-con clearfix">';
		    htm+='        <div class="comment-show-con-img pull-left headphoto"></div>';
		    htm+='        <div class="comment-show-con-list pull-left clearfix">';
		    htm+='            <div class="pl-text clearfix">';
		    htm+='                <span class="comment-size-name nickName" >'+message.nickName+': </span>';
		    htm+='                <span class="my-pl-con">&nbsp;'+message.content+'</span>';
		    htm+='            </div>';
		    htm+='            <div class="date-dz">';
		    htm+='                <span class="date-dz-left pull-left comment-time">'+message.messageDate+'</span>';
		    htm+='                <div class="date-dz-right pull-right comment-pl-block">';
		    /*htm+='                    <a href="javascript:;" class="removeBlock">删除</a>';*/
		    htm+='                    <a href="javascript:;" class="date-dz-pl pl-hf hf-con-block pull-left" data-pid="'+message.id+'" onclick="createHfKuai(this)">回复</a>';
		    htm+='                    <span class="pull-left date-dz-line">|</span>';
		    htm+='                    <a href="javascript:;" class="date-dz-z pull-left" data-id="'+message.id+'" onclick="addStar(this)"><i class="date-dz-z-click-red"></i>赞 (<i class="z-num">'+message.stars+'</i>)</a>';
		    htm+='                </div>';
		    htm+='            </div>';
		    htm+='            <div class="hf-list-con">'+loadHfInfo(message)+'</div>';
		    htm+='        </div>';
		    htm+='    </div>';
		    htm+='</div>';
		});
	}else{
		htm+=' 暂无留言！';
	}
	t.append(htm);
	//表情翻译
	show_em();
	//头像背景颜色
	setHeadphoto();
	//获取位置信息
	getLocation();
}

//回复信息加载展示
function loadHfInfo(message){
	var replyList=message.children;
	var htm =''; 
	if(replyList!=null && replyList.length>0){
        var oAt = '';
        var oHf = '';
        $.each(replyList,function(i,reply){
        	var nickName='';
        	if(reply.nickName!=null && reply.nickName!='' && reply.nickName!=undefined){
        		nickName=reply.nickName;
        	}
        	var pid=reply.id;
        	var content=reply.content;
        	var hfContent=content.substring(content.indexOf(":")+1);
        	var oHfName=content.substring(content.indexOf("@")+1,content.indexOf(":"));
        	var oHfVal = content;
        	var oAllVal = '回复@'+oHfName;
           // delete reply.content;
           // delete reply.nickName;
            var arr;
            var ohfNameArr;
            var data=new Object();
            if(oHfVal.replace(/^ +| +$/g,'') == '' || oHfVal == oAllVal){

            }else {
            	if(oHfVal.indexOf("@") == -1){
                    data['atName'] = '';
                    data['hfContent'] = oHfVal;
                }else {
                    arr = oHfVal.split(':');
                    ohfNameArr = arr[0].split('@');
                    data['hfContent'] = arr[1];
                    data['atName'] = ohfNameArr[1];
                }
            	if(data.atName == ''){
                    oAt = data.hfContent;
                }else {
                    oAt = '回复<a href="#" class="atName">@'+data.atName+'</a> : '+data.hfContent;
                }
            }
            htm+='<div class="all-pl-con">';
            htm+='	<div class="pl-text hfpl-text clearfix">';
            htm+='		<a href="#" class="comment-size-name">'+nickName+': </a>';
            htm+='		<span class="my-hf-con">'+oAt+'</span>';
            htm+='	</div>';
            htm+='	<div class="date-dz"> ';
            htm+='		<span class="date-dz-left pull-left comment-time">'+reply.messageDate+'</span> ';
            htm+='		<div class="date-dz-right pull-right comment-pl-block"> ';
            /*htm+='			<a href="javascript:;" class="removeBlock">删除</a> ';*/
            htm+='			<a href="javascript:;" class="date-dz-pl pl-hf hf-con-block pull-left" data-pid="'+pid+'" onclick="createHfKuai(this)">回复</a> ';
            htm+='			<span class="pull-left date-dz-line">|</span> ';
            htm+='			<a href="javascript:;" class="date-dz-z pull-left" data-id="'+pid+'" onclick="addStar(this)"><i class="date-dz-z-click-red"></i>赞 (<i class="z-num">'+reply.stars+'</i>)</a> ';
            htm+='		</div> ';
            htm+='	</div>';
            htm+='</div>';
            var html= loadHfInfo(reply);
            htm+=html;
        });
	}
	return htm;
}

//QQ表情展示
function show_em(){
	$(".comment-show").find(".comment-show-con-list").each(function(){
		var str = $(this).find(".my-pl-con").text();
		$(this).find(".my-pl-con").html(replace_em(str));
	}); 
}
//QQ表情代码翻译
function replace_em(str){
	str = str.replace(/\</g,'&lt;');
	str = str.replace(/\>/g,'&gt;');
	str = str.replace(/\n/g,'<br/>');
	str = str.replace(/\[em_([0-9]*)\]/g,'<img src="'+ctx+'/static/qqFace/arclist/$1.gif" border="0" />');
	return str;

}

//验证码
function loadimage(){
	document.getElementById("randImage").src=ctx+"/image.jsp?"+Math.random();
}

//评论信息提交
function submitData(){
	var nickName = $("#nickName").val();
	var content=$("#content").val();
	var email = $('#email').val();
	var imageCode=$("#imageCode").val();
	if(email ==null || email == ''){
		
	}else{
		if(!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(email)){
			confirm("您输入的email格式不正确！");
			return;
		}
	}
	if(nickName==null || nickName==''){
		alert("请输入您的昵称！");
		return;
	}else if(content==null || content==''){
		alert("请输入留言内容！");
		return;
	}else if(imageCode==null || imageCode==''){
		alert("请填写验证码！");
		return;
	}else{
		$.post(ctx+"/message/save.do",{'content':content,'nickName':nickName,'email':email,'imageCode':imageCode},function(result){
			if(result.success){
				window.location.reload();
				confirm("谢谢您的留言！");
			}else{
				confirm(result.errorInfo);
			}
		},"json");
	}
}

//头像背景颜色
function productBackgroundColor(){
    //用rgb格式生成随机的颜色，rgb每一项的数字都是0到255,因此每一项的长度为256
    //Math.random 生成0到1之间的随机数，与256相乘则会得到0到256之间的随机数
    //再用Math.floor向下取整之后，则得到的是0到255的随机整数，则rgb(r,g,b)可以实现颜色的随机性
        var r = Math.floor( Math.random()*256);
        var b = Math.floor( Math.random()*256);
        var g = Math.floor( Math.random()*256);
        return "rgb("+r+","+g+","+b+")";
}
//设置头像
function setHeadphoto(){
	for(var i=0; i<$(".comment-show").find(".headphoto").length;i++){
		$(".comment-show").find(".headphoto").eq(i).css("background-color",productBackgroundColor());
		var headphotoWord = $(".comment-show").find(".comment-show-con-list").find(".nickName").eq(i).text().charAt(0);
		if(/^[0-9a-zA-Z]$/.test(headphotoWord)){
			headphotoWord = $(".comment-show").find(".comment-show-con-list").find(".nickName").eq(i).text().substring(0,2);
		}
		$(".comment-show").find(".headphoto").eq(i).text(headphotoWord);
	}
}
//跨域调用新浪根据ip获取位置的接口（只能获取到省地市）
function getLocation(){
	for(var i=0; i<$(".comment-show").find(".locationIP").length;i++){
		var ip = $(".comment-show").find(".locationIP").eq(i).val();
		/*根据ip获取所在地的api接口，新浪接口*/
		$.ajaxSettings.async = false;
		$.get('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip='+ip,function(_result){  
			if (remote_ip_info.ret == '1'){
				if(remote_ip_info.province !== remote_ip_info.city){
					$(".comment-show").find(".location").eq(i).html("&nbsp;&nbsp;&nbsp;["+remote_ip_info.province+"省"+remote_ip_info.city+"市网友]");   
				}else{
					$(".comment-show").find(".location").eq(i).html("&nbsp;&nbsp;&nbsp;["+remote_ip_info.province+"市网友]");
				}
			} else {   
				$(".comment-show").find(".location").eq(i).html();
			}
		});
		$.ajaxSettings.async = true;
	}
}

/**
 * 评论回复js
 * @param t
 * @returns
 */
//textarea高度自适应
$(function () {
    $('.content').flexText();
});
//textarea限制字数
function keyUP(t){
    var len = $(t).val().length;
    if(len > 139){
        $(t).val($(t).val().substring(0,140));
    }
}
//点击评论创建评论条
/*function createPlTiao(){
	*//**
	 * <!--
	    此评论textarea文本框部分使用的https://github.com/alexdunphy/flexText此插件
	-->
	 * @returns
	 *//*
	$('.commentAll').on('click','.plBtn',function(){
	    var myDate = new Date();
	    //获取当前年
	    var year=myDate.getFullYear();
	    //获取当前月
	    var month=myDate.getMonth()+1;
	    //获取当前日
	    var date=myDate.getDate();
	    var h=myDate.getHours();       //获取当前小时数(0-23)
	    var m=myDate.getMinutes();     //获取当前分钟数(0-59)
	    if(m<10) m = '0' + m;
	    var s=myDate.getSeconds();
	    if(s<10) s = '0' + s;
	    var now=year+'-'+month+"-"+date+" "+h+':'+m+":"+s;
	    //获取输入内容
	    var oSize = $(this).siblings('.flex-text-wrap').find('.comment-input').val();
	    console.log(oSize);
	    //动态创建评论模块
	    var oHtml = '';
	    oHtml+='<div class="comment-show-con clearfix">';
	    oHtml+='	<div class="comment-show-con-img pull-left">';
	    oHtml+='		<img src="images/header-img-comment_03.png" alt="">';
	    oHtml+='	</div> ';
	    oHtml+='	<div class="comment-show-con-list pull-left clearfix">';
	    oHtml+='		<div class="pl-text clearfix"> ';
	    oHtml+='			<a href="#" class="comment-size-name">David Beckham : </a> ';
	    oHtml+='			<span class="my-pl-con">&nbsp;'+ oSize +'</span> ';
	    oHtml+='		</div> ';
	    oHtml+='		<div class="date-dz"> ';
	    oHtml+='			<span class="date-dz-left pull-left comment-time">'+now+'</span> ';
	    oHtml+='			<div class="date-dz-right pull-right comment-pl-block">';
	    oHtml+='				<a href="javascript:;" class="removeBlock">删除</a> ';
	    oHtml+='				<a href="javascript:;" class="date-dz-pl pl-hf hf-con-block pull-left">回复</a> ';
	    oHtml+='				<span class="pull-left date-dz-line">|</span> ';
	    oHtml+='				<a href="javascript:;" class="date-dz-z pull-left">';
	    oHtml+='					<i class="date-dz-z-click-red"></i>赞 (<i class="z-num">666</i>)';
	    oHtml+='				</a> ';
	    oHtml+='			</div> ';
	    oHtml+='		</div>';
	    oHtml+='		<div class="hf-list-con"></div>';
	    oHtml+='	</div> ';
	    oHtml+='</div>';
	    if(oSize.replace(/(^\s*)|(\s*$)/g, "") != ''){
	        $(this).parents('.reviewArea ').siblings('.comment-show').prepend(oHtml);
	        $(this).siblings('.flex-text-wrap').find('.comment-input').prop('value','').siblings('pre').find('span').text('');
	    }
	});
}*/
//点击回复动态创建回复块
function createHfKuai(obj){
	 //$('.comment-show').on('click','.pl-hf',function(){
    	//获取回复的pid
        var pid = $(obj).attr("data-pid");
        //获取回复人的名字
        var hfName = $(obj).parents('.date-dz-right').parents('.date-dz').siblings('.pl-text').find('.comment-size-name').html();
        var nickName = $("#nickName").val();
        console.log(hfName.substring(0,hfName.indexOf(":"))+"----"+nickName);
        if(nickName!=null && nickName!='' && nickName!=undefined){
        	if(hfName.substring(0,hfName.indexOf(":"))==nickName){
        		confirm("您别自己回复自己啊！");
        		return;
        	}
        }
        //回复@
        var hfN = '回复@'+hfName;
        //var oInput = $(this).parents('.date-dz-right').parents('.date-dz').siblings('.hf-con');
        var hfHtml = '';
        hfHtml+='<div class="hf-con pull-left"> ';
        hfHtml+='	<textarea class="content comment-input hf-input" placeholder="" onkeyup="keyUP(this)"></textarea>';
        hfHtml+='	<a href="javascript:;" class="hf-pl" data-pid="'+pid+'" onclick="submitHfInfo(this)">回复</a>';
        hfHtml+='</div>';
        //显示回复
        if($(obj).is('.hf-con-block')){
            $(obj).parents('.date-dz-right').parents('.date-dz').append(hfHtml);
            $(obj).removeClass('hf-con-block');
            $('.content').flexText();
            $(obj).parents('.date-dz-right').siblings('.hf-con').find('.pre').css('padding','6px 15px');
            //console.log($(this).parents('.date-dz-right').siblings('.hf-con').find('.pre'))
            //input框自动聚焦
            $(obj).parents('.date-dz-right').siblings('.hf-con').find('.hf-input').val('').focus().val(hfN);
        }else {
            $(obj).addClass('hf-con-block');
            $(obj).parents('.date-dz-right').siblings('.hf-con').remove();
        }
//    });
}

//回复信息提交服务器并创建提交后的回复块
function submitHfInfo(obj){
	//$('.comment-show').on('click','.hf-pl',function(){
    	var pid=$(obj).attr("data-pid");
    	
        //获取输入内容
        var oHfVal = $(obj).siblings('.flex-text-wrap').find('.hf-input').val();
        console.log(oHfVal)
        
        //将回复插入数据库中
        //获取回复人的信息
    	var nickName = $("#nickName").val();
		var content=oHfVal;
		var email = $('#email').val();
		var imageCode=$("#imageCode").val();
		if(email ==null || email == ''){
			
		}else{
			if(!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(email)){
				confirm("您输入的email格式不正确！");
				return;
			}
		}
		if(nickName==null || nickName==''){
			confirm("请输入您的昵称！");
			return;
		}else if(content==null || content==''){
			confirm("请输入回复内容！");
			return;
		}else if(imageCode==null || imageCode==''){
			confirm("请填写验证码！");
			return;
		}else{
			$.post(ctx+"/message/save.do",{'content':content,'nickName':nickName,'email':email,'imageCode':imageCode,'pid':pid},function(result){
				if(result.success){
					window.location.reload();
				}else{
					confirm(result.errorInfo);
					return;
				}
			},"json");
		}
 //   });
}

//删除回复块
/*function deleteHfKuai(){
	$('.commentAll').on('click','.removeBlock',function(){
        var oT = $(this).parents('.date-dz-right').parents('.date-dz').parents('.all-pl-con');
        if(oT.siblings('.all-pl-con').length >= 1){
            oT.remove();
        }else {
            $(this).parents('.date-dz-right').parents('.date-dz').parents('.all-pl-con').parents('.hf-list-con').css('display','none')
            oT.remove();
        }
        $(this).parents('.date-dz-right').parents('.date-dz').parents('.comment-show-con-list').parents('.comment-show-con').remove();

    })
}*/

//点赞
function addStar(obj){
	//$('.comment-show').on('click','.date-dz-z',function(){
	var id=$(obj).attr("data-id");
	var zNum = $(obj).find('.z-num').html();
    if($(obj).is('.date-dz-z-click')){
        zNum--;
        $(obj).removeClass('date-dz-z-click red');
        $(obj).find('.z-num').html(zNum);
        $(obj).find('.date-dz-z-click-red').removeClass('red');
    }else {
        zNum++;
        $(obj).addClass('date-dz-z-click');
        $(obj).find('.z-num').html(zNum);
        $(obj).find('.date-dz-z-click-red').addClass('red');
    }
	//封装参数
	var params=new Object();
	params.id=id;
	params.stars=zNum;
	var url= ctx+"/message/addStars.do";
	//发送请求，获取数据
	$.ajax({
	    url:url,
	    type: "POST",
	    async: true,
	    data: params,
	    success: function (data) { 
	    	var result=eval('('+data+')');
	        var success=result.success;
	        if(success==true){
	            
	        }else{
	        	confirm("系统异常！","fail");
	        }	
	    },
	    error: function (XmlHttpRequest, textStatus, errorThrown) {
	        console.log("系统异常！");
	        confirm("系统异常！","fail");
	    },
	    complete:function(XMLHttpRequest, textStatus){
			console.log("url:[ "+url+" ] 请求结果：[ "+textStatus+" ]");
			//关闭加载提示
			//alert(layindex);
		}
	});
   // })
}